package com.umbrella.worker.web.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.umbrella.worker.dto.AttachmentDO;
import com.umbrella.worker.result.ResultDO;
import com.umbrella.worker.result.ResultSupport;
import com.umbrella.worker.service.IAttachmentService;

@Controller
@RequestMapping(value = "/attach")
public class AttachController {
	
	@Autowired
	private IAttachmentService attachmentService;

	@RequestMapping(value = "/images/{id}.jpg", method = RequestMethod.GET)
	public void viewAttach(@PathVariable(value="id") Integer id,
    		HttpServletRequest request,
    		HttpServletResponse response) {
		ResultDO result = attachmentService.get(id);
		if(result.isSuccess()) {
			AttachmentDO attach = (AttachmentDO) result.getModel(ResultSupport.FIRST_MODEL_KEY);
			String filePath = attach.getwAttachPath();
			String fileName = attach.getwAttachName();
			FileInputStream in = null;
			OutputStream out = null;
			try {
			
				in = new FileInputStream(filePath + fileName);
				 response.setContentType("img/*");
				 out = response.getOutputStream();
				 int b = 0;
				 while((b = in.read()) != -1) {
					 out.write(b);
				 }
				 out.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					in.close();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
